package eu.szemraj.data.collections.stack {
    import eu.szemraj.data.collections.iterators.ProtectedIterator;    
    import eu.szemraj.data.collections.iterators.IIterator;    
    import eu.szemraj.data.collections.iterators.ArrayIterator;    
    import eu.szemraj.data.collections.stack.IStack;
    
    public class Stack implements IStack {

		protected var values:Array = null;

        public function Stack( source:Array = null ) {
        	
        	if( source ) {
        		
                values = source.concat();
            }
            else {
            	
            	values = [];
            	
            }
        	
        }
        
        public function push(value:*):void {
        	
            values.push( value );
        }
        
        public function pop():* {
        	
            if( empty ) {
            	
            	throw new Error( "You tried to pop an element from an empty Stack." );
            	
            }
            return values.pop();
        }
        
        public function peek():* {
        	
             if( empty ) {
            	
            	throw new Error( "You tried to peek an element from an empty Stack." );
            	
            }
            return values[ values.length - 1 ];
        }
        
        public function get size():int {
        	
            return values.length;
        }
        
        public function get empty():Boolean {
        	
            return size == 0;
        }
        
        public function toArray():Array {
        	
            var result:Array = values.concat();
			result.reverse();
			return result;
			
        }
        
        public function iterator():IIterator {
        	
            var reversedValues:Array = values.slice();
			reversedValues.reverse();
			return new ProtectedIterator( new ArrayIterator(reversedValues) );
		}				public function clear():void {
			
			values = null;
		}
	}
}
